package com.yonyou.iuap.base.sl;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ParseJsontoPsw {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());

    public boolean parseJson(String json) {
    	
    	Md5Util md5 = new Md5Util();
    	JSONObject jsonObject = JSONObject.fromObject(json);
        String str = "";
        String data = null;
        try {
            if (json==null || "".equals(json)) {
                return false;
            }
            data = jsonObject.getString("data");
            String ipAddress = jsonObject.getString("ipAddress");
            String platform = jsonObject.getString("platform");
            String timestamp = jsonObject.getString("timestamp");
            String version = jsonObject.getString("version");
            String userid = jsonObject.getString("userid");
            String sign = jsonObject.getString("sign");
            str = "data=" + data + "&" + "ipAddress=" + ipAddress + "&" + "platform=" + platform + "&" + "timestamp="
            		+ timestamp + "&" + "version=" + version + "&" + "userid=" + userid;
            String psw;
            String str1 = string2Unicode(str);
            psw = md5.encrypt(str1);
            
            if (psw.equals(sign)) {
            	return true;
            } else {
            	return false;
            }
        } catch (Exception e) {
        	logger.error(e.getMessage());
            return false;
        }
        

    }

    /**
     * 字符串转换unicode
     * 
     * @param str
     * @return
     */
    private static String string2Unicode(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            // 取出每一个字符
            char c = str.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    public String encryptJson(String data, String ipAddress, String platform, String timestamp, String version) {
        Md5Util md5 = new Md5Util();

        String str = "";

        str = "data=" + data + "&" + "ipAddress=" + ipAddress + "&" + "platform=" + platform + "&" + "timestamp="
                + timestamp + "&" + "version=" + version;
        String str1 = null;

        try {
        	str1 = string2Unicode(str);
        } catch (Exception e) {
            return null;
        }
        String sign = md5.encrypt(str1);
        return sign;
    }
}
